<template>
  <el-dialog
    title="选择用户"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    destroy-on-close
    append-to-body
    class="business-dialog"
    :close-on-click-modal="false"
  >
    <div class="wrapper">
      <div class="search-container">
        <el-input
          placeholder="输入关键字进行过滤"
          clearable
          v-model="searchKey"
          size="mini"
          style="width: 360px"
          @keyup.enter.native="filterNode"
        >
          <el-button slot="append" icon="el-icon-search" @click.prevent="filterNode"></el-button>
        </el-input>
      </div>
      <div class="tree-container">
        <el-tree
          ref="syncTree"
          v-show="syncTreeVisible"
          :node-key="'id'"
          :data="treeData"
          show-checkbox
          check-strictly
          default-expand-all
          @check-change="selectTreeNode"
          v-loading="fetchLoading"
        >
        </el-tree>
        <el-tree
          :props="{ isLeaf: 'isLeaf' }"
          ref="asyncTree"
          v-show="!syncTreeVisible"
          :node-key="'id'"
          :load="loadNode"
          lazy
          show-checkbox
          :check-strictly="true"
          @check-change="selectTreeNode"
          v-loading="fetchLoading"
        >
        </el-tree>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="small" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import { getFirstLevelOrgList, qryOrgListByParentOrgId, qryEmployeeListByOrgId } from '@/api'
import { selectOrgTreeByCondition, modifyCollaborator } from '@/api'

export default {
  name: 'UserSelectionModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchKey: '',
      treeData: [],
      syncTreeVisible: false,
      dialogVisible: this.visible,
      fetchLoading: false
    }
  },
  methods: {
    show() {
      this.treeData = []
      this.searchKey = ''
      this.dialogVisible = true
    },
    async filterNode() {
      if (this.searchKey) {
        this.syncTreeVisible = true
        this.fetchLoading = true
        try {
          const data = await selectOrgTreeByCondition({ searchKey: this.searchKey })
          this.fetchLoading = false
          this.treeData = data
        } catch (error) {
          this.fetchLoading = false
          this.treeData = []
        }
      } else {
        this.syncTreeVisible = false
      }
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.fetchLoading = true
        return getFirstLevelOrgList()
          .then(resolve)
          .finally(() => (this.fetchLoading = false))
      }
      if (node.data.isLeaf) {
        if (node.data.isOrgNode) {
          this.fetchLoading = true
          return qryEmployeeListByOrgId({ orgId: node.data.orgId })
            .then(resolve)
            .finally(() => (this.fetchLoading = false))
        }
        return resolve([])
      }
      const { orgId, orgCode } = node.data
      this.fetchLoading = true
      return Promise.all([
        qryEmployeeListByOrgId({ orgId }),
        qryOrgListByParentOrgId({ parentOrgId: orgId, parentOrgCode: orgCode })
      ])
        .then(([e, o]) => {
          resolve([...e, ...o])
        })
        .finally(() => {
          this.fetchLoading = false
        })
    },
    async handleConfirm() {
      const checkedNodes = this.syncTreeVisible
        ? this.$refs.syncTree.getCheckedNodes()
        : this.$refs.asyncTree.getCheckedNodes()
      if (checkedNodes.length !== 1 || !checkedNodes[0]?.data?.userId) {
        Message.warning('请选择单个用户')
        return
      }
      this.$emit('onChange', checkedNodes[0]?.data)
      this.handleClose()
    },
    handleClose() {
      this.dialogVisible = false
      this.$emit('update:visible', false)
    },
    selectTreeNode(data, checked) {
      if (checked && data.isUserNode) {
        this.syncTreeVisible
          ? this.$refs.syncTree.setCheckedNodes([data])
          : this.$refs.asyncTree.setCheckedNodes([data])
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding-top: 0;
  padding-bottom: 10px;
  max-height: 500px;
  overflow: auto;
}
.wrapper {
  height: 480px;
  font-family: 'microsoft yahei';
}
.wrapper .search-container {
  height: 40px;
}
.wrapper .tree-container {
  height: 440px;
  overflow: auto;
  width: 100%;
}
::v-deep .el-tree-node .el-checkbox .el-checkbox__inner {
  display: none;
}
::v-deep .el-tree-node .is-leaf + .el-checkbox .el-checkbox__inner {
  display: block;
}
</style>
